// index.js
// 获取应用实例
import dayjs from "dayjs";
const app = getApp()
var QQMapWX = require('../../libs/qqmap-wx-jssdk');

// 实例化API核心类
let qqmapsdk = new QQMapWX({
  key: 'HUGBZ-6GTKK-WUHJD-AMKI2-AGTX5-35BW4'
});

//空图表初始化
let chart = null;
const data = [];

function initChart(canvas, width, height, F2) { // 使用 F2 绘制图表
  //实例化图表
  chart = new F2.Chart({
    el: canvas,
    width,
    height
  });
  //装载数据   
  // 配置纵坐标temp项的样式
  chart.axis('temp', {
    label: {
      fill: '#4B4D50',
    }
  });
  // 配置横坐标hour项的样式
  chart.axis('hour', {
    tickLine: {
      length: 4,
      stroke: '#4D8CF4'
    },
    label: {
      fill: '#393939'
    }
  });
  chart.source(data, {
    temp: {
      tickCount: 3,
      //后面添加温度 °C
      formatter: function (val) {
        return val + '°C';
      },
    },
    hour: {
      tickCount: 4 //间隔显示
    }
  });
  // 配置提示信息
  chart.tooltip({
    showItemMarker: false,
    showCrosshairs: true,
    background: {
      radius: 2,
      padding: [3, 5],
      fill: '#2D9EFC'
    },
    nameStyle: {
      fill: '#fff'
    },
  });
  //画图-柱状图、折线图、饼图...   
  chart.line().position('hour*temp');
  // 给每个温度添加一个圆点
  chart.point().position('hour*temp').style({
    stroke: '#eee',
    lineWidth: 1,
    fillOpacity: 0.7
  }); // 重新定义图形语法  
  chart.render();
  return chart;
}

Page({
  data: {
    // 城市(默认)
    cityName: '北京市',
    // location: '',
    //天气信息
    weatherInfo: {},
    //提示
    // tips: '',
    //24小时
    hourly: [],
    //七天
    days: [],
    //生活指数
    daily: [],
    //经纬度
    latitude: '',
    longitude: '',
    loading: false,
    //图表
    opts: {
      onInit: initChart
    },
    //icon生活
    images: [{
        Src: '/images/run.png'
      },
      {
        Src: '/images/car.png'
      },
      {
        Src: '/images/icon4.png'
      },
      {
        Src: '/images/icon3.png'
      },
      {
        Src: '/images/icon2.png'
      },
      {
        Src: '/images/icon.png'
      },
    ],
  },

  onLoad(src) {
    const that = this
    if (src.city != null) {
      // 经纬度位置需要转换成两位小数点 
      that.setData({
        latitude: src.latitude,
        longitude: src.longitude,
        cityName: src.city,
      })
      that.getNowWeather()
      that.getHoursWeather()
      that.getDaysWeather()
      that.getLeftWeather()
    } else {
      wx.authorize({
        scope: 'scope.userLocation',
        success: (res) => {
          console.log('成功', res)
          if (res.errMsg === 'authorize:ok') {
            setTimeout(function () {
              wx.showToast({
                title: '加载中',
                icon: 'loading',
                duration: 1000
              })
            }, that.getAddress(), 1000)
          }
        },
        fail: (err) => {
          setTimeout(function () {
            wx.showToast({
              title: '加载中',
              icon: 'loading',
              duration: 1000
            })
          }, that.addresss(), 1000)
        }
      })
    }
    //显示当前页面的转发按钮
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  // 默认定位
  addresss() {
    const that = this
    that.setData({
      latitude: '40.002411349',
      longitude: '116.208660674',
    })
    that.getNowWeather()
    that.getHoursWeather()
    that.getDaysWeather()
    that.getLeftWeather()
  },

  // 用户定位
  getAddress() {
    const that = this
    qqmapsdk.reverseGeocoder({
      success: function (res) {
        console.log("位置", res.result)
        const long = res.result
        that.setData({
          cityName: long.address_component.city,
          longitude: long.ad_info.location.lng,
          latitude: long.ad_info.location.lat,
        })
      },
      fail: function (res) {
        console.log(res)
        if (res.status === 1000) {
          wx.showModal({
            title: '您的手机定位功能没有开启',
            content: '请在系统设置中打开定位服务',
            success: (result) => {
              if (result.confirm === true) {
                wx.reLaunch({
                  url: '/pages/index/index',
                })
              }
            },
            fail: (res) => {
              that.setData({
                loading: true,
              });
            },
            complete: (res) => {},
          })
        }
        that.setData({
          loading: true,
        });
      },
      complete: function (res) {
        that.getNowWeather()
        that.getHoursWeather()
        that.getDaysWeather()
        that.getLeftWeather()
      }
    })
  },

  /**
   * 点击跳转city
   */
  toCity() {
    wx.reLaunch({
      url: '/pages/city/city?location=' + this.data.longitude + ',' + this.data.latitude + '&city=' + this.data.cityName,
    })
  },
  /**
   * 点击跳转生活指数
   */
  toMore() {
    wx.navigateTo({
      url: '/pages/info/info?location=' + this.data.longitude + ',' + this.data.latitude,
    })
  },

  /**
   * 查询实时天气方法
   */
  getNowWeather: function () {
    const that = this;
    wx.request({
      url: `https://devapi.qweather.com/v7/weather/now?key=735ec7072891465597cfbd44248d6380&location=${this.data.longitude},${this.data.latitude}`,
      success: res => {
        // console.log('实时天气', res)
        // let tips = ''
        // if (res.data.now.text === '晴' || res.data.now.text === '阴' || res.data.now.text === '多云' || res.data.now.text === '霾' || res.data.now.text === '雾') {
        //   tips = '今天没有雨，放心出门吧'
        // } else if (res.data.now.text === '雨' || res.data.now.text === '小雨') {
        //   tips = '今天有雨，记得带伞噢'
        // } else if (res.data.now.text === '雪') {
        //   tips = '今天有雪，带不带伞由你咯'
        // }
        that.setData({
          weatherInfo: res.data.now,
          // tips: tips
        })
      },
      fail: err => {
        console.log(err)
      }
    })
  },

  /**
   * 查询未来24小时方法
   */
  getHoursWeather: function () {
    const that = this
    wx.request({
      url: `https://devapi.qweather.com/v7/weather/24h?key=735ec7072891465597cfbd44248d6380&location=${this.data.longitude},${this.data.latitude}`,
      success: res => {
        console.log(res.data.hourly)
        // 获取到时间数据
        let time = res.data.hourly
        let arr = []
        time.forEach((item) => {
          item.fxTime = item.fxTime.substring(11, 16)
        });
        for (let i = 0; i < time.length; i++) {
          arr.push({
            hour: res.data.hourly[i].fxTime,
            temp: parseInt(res.data.hourly[i].temp)
          })
        }
        setTimeout(function () {
          chart.changeData(arr)
          console.log(arr)
        }, 50)
        if (arr[0].hour) {
          arr[0].hour = '今天' + res.data.hourly[0].fxTime.substring(0, 2) + '点'
        }
        if (arr[8].hour) {
          arr[8].hour = '今天' + res.data.hourly[8].fxTime.substring(1, 2) + '点'
        } else if (parseInt(arr[8].hour) >= 0 && parseInt(arr[8].hour) < 6) {
          arr[8].hour = '明天' + res.data.hourly[8].fxTime.substring(1, 2) + '点'
        }
        if (arr[16].hour) {
          arr[16].hour = '明天' + res.data.hourly[16].fxTime.substring(1, 2) + '点'
        }
        if (arr[23].hour) {
          arr[23].hour = '明天' + res.data.hourly[23].fxTime.substring(1, 2) + '点'
        }
        that.setData({
          hourly: res.data.hourly,
        })
      },
    })
  },

  /**
   * 未来7天天气
   */
  getDaysWeather: function () {
    const that = this
    wx.request({
      url: `https://devapi.qweather.com/v7/weather/7d?key=735ec7072891465597cfbd44248d6380&location=${this.data.longitude},${this.data.latitude}`,
      success: res => {
        let weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
        for (const item of res.data.daily) {
          item.fxDate = weeks[dayjs(item.fxDate).day()];
        }
        if (res.data.daily[0].fxDate) {
          res.data.daily[0].fxDate = "今天"
        }
        if (res.data.daily[1].fxDate) {
          res.data.daily[1].fxDate = "明天"
        }
        if (res.data.daily[2].fxDate) {
          res.data.daily[2].fxDate = "后天"
        }
        that.setData({
          days: res.data.daily
        })
      }
    })
  },

  /**
   * 获取生活指数
   */
  getLeftWeather: function () {
    const that = this
    wx.request({
      url: `https://devapi.qweather.com/v7/indices/1d?type=2,3,4,1,9,14&location=${this.data.longitude},${this.data.latitude}&key=735ec7072891465597cfbd44248d6380`,
      success: res => {
        console.log(res)
        let names = res.data.daily
        names.forEach((item) => {
          item.name = item.name.substring(0, 2)
        })
        that.setData({
          daily: res.data.daily,
        })
      }
    })
  },

  /**
   * 下拉刷新响应事件
   */
  onPullDownRefresh: function () {
    const that = this
    setTimeout(function () {
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, 1000);
    that.getNowWeather()
    that.getHoursWeather()
    that.getDaysWeather()
    that.getLeftWeather()
  }

})